package com.spark.data

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.error
import com.spark.common.ext.wrapIO
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.data.model.BorrowListModel
import kotlinx.android.synthetic.main.frag_borrow_child.*

/**
 * 借阅清单-子条目
 */
class BorrowChildFragment : BaseFragment() {
    private var index = 0
    private var currPage = 1
    private lateinit var dateQrItemAdapter: DateQrItemAdapter

    companion object {
        fun newInstance(index: Int): BorrowChildFragment {
            val fragment = BorrowChildFragment()
            val args = Bundle()
            args.putInt(Const.tag_index, index)
            fragment.arguments = args
            return fragment
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_borrow_child
    }

    @SuppressLint("MissingSuperCall")
    override fun onAttach(context: Context?) {
        super.onAttach(context)
        index = arguments?.getInt(Const.tag_index) ?: 0
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        dateQrItemAdapter = DateQrItemAdapter(R.layout.item_borrow_list)
        recy_borrows.adapter = dateQrItemAdapter
        recy_borrows.layoutManager = LinearLayoutManager(activity)

        refresh_layout.setOnRefreshListener {
            currPage = 1
            fetchBorrowList(currPage)
        }
        refresh_layout.setOnLoadmoreListener {
            currPage++
            fetchBorrowList(currPage)
        }
        fetchBorrowList(currPage)

        dateQrItemAdapter.setOnItemChildClickListener { _, _, position ->
            val item = dateQrItemAdapter.data[position]
            val itemStr = Gson().toJson(item)
            //activity?.apply { start(ApplyInfoFragment.newInstance(itemStr)) }
            activity?.apply { ApplyInfoActivity.actionStart(this, itemStr) }
        }

        dateQrItemAdapter.addData(
                mutableListOf(
                        BorrowListModel.ResultMap(),
                        BorrowListModel.ResultMap(),
                        BorrowListModel.ResultMap(),
                        BorrowListModel.ResultMap(),
                        BorrowListModel.ResultMap(),
                        BorrowListModel.ResultMap()
                )
        )
    }

    /**
     * 获取借阅清单列表
     */
    @SuppressLint("CheckResult")
    private fun fetchBorrowList(page: Int) {
        val params = mutableMapOf(
                Pair(Const.qr_taskType, "3"),
                Pair(Const.qr_state, "$index"),
                Pair(Const.qr_pageNum, "$page"),
                Pair(Const.qr_pageSize, "10"))
        Http.request()
                .rxPost("${Const.base_url}${Const.act_get_borrow_list}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, BorrowListModel::class.java)?.apply {
                                if (code == "200") {
                                    if (page == 1)
                                        dateQrItemAdapter.data.clear()
                                    dateQrItemAdapter.addData(this.resultMaps)

                                } else {
                                    error(msg)
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            if (page == 1) refresh_layout.finishRefresh() else refresh_layout.finishLoadmore()
                        },
                        {
                            if (page == 1) refresh_layout.finishRefresh() else refresh_layout.finishLoadmore()
                        },
                        {
                            dispose = it
                        }
                )
    }
}

class BorrowBookAdapter(layoutRes: Int, var eyeOpen: Boolean = true) : BaseQuickAdapter<BorrowListModel.ResultMap.File, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: BorrowListModel.ResultMap.File?) {
        if (item == null) return
        helper?.apply {
            setText(R.id.tv_name, item.filename)
            setGone(R.id.ll_eye, eyeOpen)
        }
    }

}